package com.abluedog.c2;

import com.abluedog.util.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;

import static com.abluedog.util.ByteBufferUtil.debugAll;

@Slf4j
public class Server {

    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));
        serverSocketChannel.configureBlocking(false);
        // 注册serverSocketChannel 与  selector 的联系
        SelectionKey sscKey = serverSocketChannel.register(selector, 0, null);
        log.debug("sscKey:{}", sscKey);
        // 只关注 accept 事件
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
//        ArrayList<SocketChannel> channels = new ArrayList<>();
        while (true) {
            //没有事件 线程阻塞 有事件未处理也不会阻塞
            selector.select();
            // 处理事件
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                // 处理完一个事件，就删除
                iterator.remove();
                // 取消事件
                // next.cancel();
                log.debug("event:{}", key);
                // 处理事件
                if (key.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    ByteBuffer byteBuffer = ByteBuffer.allocate(5);
                    //byteBuffer作为附件关联
                    SelectionKey scKey = sc.register(selector, 0, byteBuffer);
                    scKey.interestOps(SelectionKey.OP_READ);
                    log.debug("connected...{}", sc);
                }else if (key.isReadable()) {
                    try {
                        ByteBuffer byteBuffer = (ByteBuffer)key.attachment();
                        SocketChannel channel = (SocketChannel) key.channel();
                        int read = channel.read(byteBuffer);
                        //如果是正常断开 read 返回 -1
                        if (read == -1){
                            log.debug("closed...{}", channel);
                            // 取消事件
                            key.cancel();
                        }else {
                            split(byteBuffer);
                            if (byteBuffer.position() == byteBuffer.limit()){
                                ByteBuffer newByteBuffer = ByteBuffer.allocate(byteBuffer.capacity() * 2);
                                byteBuffer.flip();
                                newByteBuffer.put(byteBuffer);
                                key.attach(newByteBuffer);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        key.cancel();
                    }
                }
            }
//            SocketChannel channel = serverSocketChannel.accept();
//            if (channel != null) {
//                log.debug("connected...{}", channel);
//                channel.configureBlocking(false);
//                channels.add(channel);
//            }
//            for (SocketChannel client : channels) {
//                int read = client.read(allocate);
//                if (read > 0) {
//                    log.debug("after read...{}", client);
//                    allocate.flip();
//                    ByteBufferUtil.debugRead(allocate);
//                    allocate.clear();
//                }
//            }
        }
    }

    private static void split(ByteBuffer byteBuffer) {
        byteBuffer.flip();
        for (int i = 0; i < byteBuffer.limit(); i++) {
            if (byteBuffer.get(i) == '\n') {
                int length = i + 1 - byteBuffer.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    target.put(byteBuffer.get());
                }
                debugAll(target);
            }
        }
        byteBuffer.compact();
    }
}
